package emby.stmt;

import emby.EmbyRuntime;
import emby.expr.Expression;
import emby.lang.Block;
import emby.lang.Scope;
import emby.writer.IEmbyCodifier;

public class While extends Statement{

	private static final long serialVersionUID = -5365813469631952104L;
	Expression condition;
	Block body;
	public While(Expression _condition, Block _body){
		condition = _condition;
		body = _body;
	}

	private boolean isConditionTrue(Scope s){
		Object o = condition.eval(s);
		if( o==null) return false;
		if( o==Boolean.FALSE) return false;
		if( o instanceof Number) return ((Number)o).doubleValue()!=0;
		return true;
	}

	/**
	 * Always returns null UNLESS there was a return statement in the block.
	 */
	@Override
	public Object eval(Scope s) {
		//Scope subscope = new Scope(s);
		if(EmbyRuntime.echo){
			emby.util.Print.println("Evaluating while loop. Condition: "+condition);
		}
		while( isConditionTrue(s)){
			Object retValue = body.eval(s);
			if(retValue!=null){
				return retValue;
			}
		}
		return null;
	}
	
	public void codify(IEmbyCodifier ec){
		ec.while_(condition, body);
	}
}
